/**
 * 
 */
package habitcoach.core.habit.storer;

import habitcoach.core.habit.Habit;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Coddy created on 2010-5-2
 * 
 */
public class HabitSerializableStorer implements HabitStorer
{
	private static HabitSerializableStorer instance;
	static final String DEFAULT_FILE_NAME = "habits.dat";

	private HabitSerializableStorer()
	{

	}

	public static HabitSerializableStorer getInstance()
	{
		if (instance == null)
		{
			synchronized (HabitSerializableStorer.class)
			{
				if (instance == null)
				{
					instance = new HabitSerializableStorer();
				}
			}
		}
		return instance;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * habitcoach.core.habit.storer.HabitStorer#loadHabits(java.lang.String)
	 */
	@Override
	public List<Habit> loadHabits(String destination)
	{
		// TODO Auto-generated method stub
		List<Habit> list = new ArrayList<Habit>();
		FileInputStream f;
		try
		{
			FileInputStream in = new FileInputStream(DEFAULT_FILE_NAME);
			ObjectInputStream s = new ObjectInputStream(in);
			list = (List<Habit>) s.readObject();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see habitcoach.core.habit.storer.HabitStorer#saveHabits(java.util.List)
	 */
	@Override
	public void saveHabits(List<Habit> habitList)
	{
		FileOutputStream f;
		try
		{
			f = new FileOutputStream(DEFAULT_FILE_NAME);
			ObjectOutputStream s = new ObjectOutputStream(f);
			s.writeObject(habitList);
			s.flush();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
